<script lang="ts" setup>
import type { flowableForm, LeaveAuditors } from '@/index.d';
import {
  getOneByCondition,
  insertOne,
  updateOne,
  urls,
  getLoginUserInfo,
  useTabsViewStore
} from '@/index';
import type { FormRules } from 'element-plus';
import { useRoute } from 'vue-router';
import router from '@/router';

const { loginUserUsername } = getLoginUserInfo();

const props = defineProps({
  processInstanceId: String,
  leaveAuditors: Object as PropType<LeaveAuditors>,
  isEditable: Boolean
});

const processDefinitionKey = computed<string>(() => {
  const res = useRoute().fullPath.split('/');
  return res[res.length - 1];
});

const leaveForm = reactive<flowableForm.LeaveForm>({
  processInstanceName: '殷红旗的请假流程',
  username: 'jilonghua',
  days: 2,
  kind: '公休',
  reason: '度假',
  departmentId: 1,
  processDefinitionKey: processDefinitionKey.value,
  processInstanceId: props.processInstanceId,
  loginUsername: loginUserUsername,
  startDate: '',
  endDate: ''
});

const setLeaveForm = (data: flowableForm.LeaveForm) => {
  leaveForm.id = data.id;
  leaveForm.processInstanceId = data.processInstanceId;
  leaveForm.processInstanceName = data.processInstanceName;
  leaveForm.username = data.username;
  leaveForm.departmentId = data.departmentId;
  leaveForm.startDate = data.startDate;
  leaveForm.endDate = data.endDate;
  leaveForm.days = data.days;
  leaveForm.kind = data.kind;
  leaveForm.reason = data.reason;
  leaveForm.businessId = data.businessId;
  leaveForm.processDefinitionId = data.processDefinitionId;
  leaveForm.processDefinitionKey = data.processDefinitionKey;
  leaveForm.businessId = data.businessId;
  leaveForm.creator = data.creator;
  leaveForm.creatorId = data.creatorId;
  leaveForm.createTime = data.createTime;
  leaveForm.updater = data.updater;
  leaveForm.updaterId = data.updaterId;
  leaveForm.updateTime = data.updateTime;
};

const timeRange = computed({
  get: () => [leaveForm.startDate, leaveForm.endDate],
  set: value => ([leaveForm.startDate, leaveForm.endDate] = value)
});

watch(
  () => props.processInstanceId,
  async (value: string | undefined) => {
    if (value) {
      const res = (await getOneByCondition<flowableForm.LeaveForm>(
        urls.leave,
        'processInstanceId',
        value
      )) as flowableForm.LeaveForm;
      setLeaveForm(res);
    }
  },
  {
    immediate: true
  }
);

interface LeaveFormRule {
  processInstanceName: string;
  username: string;
  days: string;
  startDate: string;
  timeRange: string;
  reason: string;
  kind: string;
}

const leaveFormRules = reactive<FormRules<LeaveFormRule>>({
  processInstanceName: [{ required: true, message: '请填写请假流程名称', trigger: 'blur' }],
  username: [{ required: true, message: '请选择请假人员', trigger: 'blur' }],
  days: [{ required: true, message: '请填写请假天数', trigger: 'blur' }],
  startDate: [{ required: true, message: '请选择请假日期', trigger: 'blur' }],
  reason: [{ required: true, message: '请填写请假理由', trigger: 'blur' }],
  kind: [{ required: true, message: '请填写选择请假种类', trigger: 'blur' }]
});

const leaveFormRef = ref();

const insertFormData = async () => {
  const res = (await insertOne<flowableForm.LeaveForm>(
    urls.leave,
    leaveForm
  )) as flowableForm.LeaveForm;
  if (res) {
    setLeaveForm(res);
    router.push(`/flowable/form/${res.processDefinitionKey}/${res.processInstanceId}`);
    useTabsViewStore().removeByPath('/flowable/form/leave');
  }
};

const updateFormData = async () => {
  const dataTem: flowableForm.LeaveForm = {
    id: leaveForm.id,
    kind: leaveForm.kind,
    reason: leaveForm.reason,
    processInstanceId: leaveForm.processInstanceId,
    processInstanceName: leaveForm.processInstanceName,
    startDate: leaveForm.startDate,
    endDate: leaveForm.endDate
  };
  const res = (await updateOne<flowableForm.LeaveForm>(
    urls.leave,
    dataTem
  )) as flowableForm.LeaveForm;
  setLeaveForm(res);
};

const handleSaveFormData = async () => {
  if (!leaveFormRef.value) return;
  leaveFormRef.value
    .validate()
    .then(async (valid: boolean) => {
      if (valid) {
        leaveForm.id ? updateFormData() : insertFormData();
      }
    })
    .catch((res: any) => console.log(res));
};

defineExpose({ handleSaveFormData });
</script>
<template>
  <hq-form :model="leaveForm" :rules="leaveFormRules" ref="leaveFormRef">
    <el-form-item label="流程名称" prop="processInstanceName">
      <el-input v-model="leaveForm.processInstanceName" :readonly="!isEditable" />
    </el-form-item>
    <el-row :gutter="5">
      <HqCol v-show="true">
        <el-form-item label="id" prop="id">
          <el-input v-model="leaveForm.id" readonly />
        </el-form-item>
      </HqCol>
      <HqCol>
        <el-form-item label="请假人员" prop="username">
          <el-select
            v-model="leaveForm.username"
            filterable
            :disabled="!isEditable || props.processInstanceId !== undefined"
          >
            <hq-user-options />
          </el-select>
        </el-form-item>
      </HqCol>
      <HqCol>
        <el-form-item label="部门">
          <HqCascaderDepartment
            v-model:current="leaveForm.departmentId"
            :disabled="!isEditable || props.processInstanceId !== undefined"
          />
        </el-form-item>
      </HqCol>
      <HqCol>
        <el-form-item label="请假天数" prop="days">
          <el-input-number
            v-model="leaveForm.days"
            :min="1"
            :max="30"
            :disabled="!isEditable || props.processInstanceId !== undefined"
          />
        </el-form-item>
      </HqCol>
      <HqCol>
        <el-form-item label="时间范围" prop="startDate">
          <el-date-picker
            v-model="timeRange"
            type="daterange"
            unlink-panels
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :disabled="!isEditable || props.processInstanceId !== undefined"
          />
        </el-form-item>
      </HqCol>
      <HqCol>
        <el-form-item label="请假种类" prop="kind">
          <el-select v-model="leaveForm.kind" :disabled="!isEditable">
            <HqVacationTypeOptions />
          </el-select>
        </el-form-item>
      </HqCol>
    </el-row>
    <el-form-item label="请假理由" prop="reason">
      <el-input
        v-model="leaveForm.reason"
        type="textarea"
        :rows="5"
        resize="none"
        :readonly="!isEditable"
      />
    </el-form-item>
  </hq-form>
</template>
<style lang="scss" scoped></style>
